package polyu.comp;

import java.io.*;
import java.net.*;

import android.content.*;
import android.util.*;

public class Util {
	
	public static String uid = "jason";
	public static String ip = "10.0.2.2";
	public static int	 cachep = 30;
	
	// preference updated
	public static void updateData(Context ct) {
		String fileName = ct.getResources().getString(R.string.app_name);
		SharedPreferences settings = ct.getSharedPreferences(fileName, 0);
		
		Util.uid = settings.getString("uid", "jason");
		Util.ip = settings.getString("ip", "10.0.2.2");
		Util.cachep = settings.getInt("cachep", 30);
	
	}
	
	public static void updatePref(Context ct) {
		String fileName = ct.getResources().getString(R.string.app_name);
		SharedPreferences settings = ct.getSharedPreferences(fileName, 0);
		SharedPreferences.Editor editor = settings.edit();
		
		editor.putString("uid", Util.uid);
		editor.putString("ip", Util.ip);
		editor.putInt("cachep", Util.cachep);
		
		editor.apply();
	}
	
	public static String netRequest(String cmd) {
		Socket s;
		String ret = "";
		try {
			s = new Socket(Util.ip, 4009);
			PrintWriter out = new PrintWriter(s.getOutputStream(), true);
			BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
			
			out.println(cmd);
			ret = in.readLine();
			
			out.close();
			in.close();
			s.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return ret;
	}
	
	
	public static void fTest(Context cx){
		
		String retall = Util.netRequest("friend all");
		String retfollow = Util.netRequest(String.format("friend follow %s", Util.uid));
		String retfollower = Util.netRequest(String.format("friend follower %s", Util.uid));
		

		try {
			FileOutputStream fos = cx.openFileOutput(DataManager.f_user, Context.MODE_PRIVATE);
			PrintWriter out = new PrintWriter(fos, true);
			
			out.println(retall.substring(3));
			out.println(retfollow.substring(3));
			out.println(retfollower.substring(3));
			
			out.close();
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	

}
